<template>
  <div class="mt20">
    <el-card class="box-card mt20" :body-style="{ padding: '18px 0px 5px', boxSizing: 'border-box' }">
      <el-row class="title">
        <el-col :lg="2" class="tac module-title ml20">
          <el-input placeholder="渠道cid" @change="searchWyServer" clearable v-model.trim="queryServerInfo.cid"></el-input>
        </el-col>
        <el-col :lg="5" class="tac module-title ml20" style="width: 360px">
          <el-date-picker
            v-model="queryTime"
            @change="searchWyServer"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-col>

        <el-col :lg="3" class="tal module-title ml20">
          <el-button plain type="primary" @click="reset">重置</el-button>
        </el-col>
        <el-col :lg="6" class="tar module-title">
          <el-button plain type="primary" @click="downloadExcel(false)" :loading="downloadLoading1">导出当前页</el-button>
          <el-button plain type="primary" @click="downloadExcel(true)" :loading="downloadLoading2">导出所有页</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="tableData"
        :height="tableHeight"
        :loading="tableLoading"
        :show-summary="true"
        :summary-method="getSummaries"
        ref="table_cid"
        row-key="index"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="序号" type="index"> </el-table-column>
        <el-table-column prop="cid" label="cid">
          <template slot-scope="scope">
            <a @click="goCCID(scope.row)" style="color: #409eff; cursor: pointer">{{ scope.row.cid }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="totalcost" label="消耗"> </el-table-column>
        <el-table-column prop="reg_nums" label="注册"> </el-table-column>
        <el-table-column prop="reg_rate" label="访问转化率"> </el-table-column>
        <el-table-column prop="reg_price" label="注册单价"> </el-table-column>
        <el-table-column prop="role_nums" label="创角"> </el-table-column>
        <el-table-column prop="role_rate" label="创角率"> </el-table-column>
        <el-table-column prop="order_nums" label="充值人数"> </el-table-column>
        <el-table-column prop="order_money" label="充值金额"> </el-table-column>
        <el-table-column prop="order_rate" label="付费率"> </el-table-column>
        <el-table-column prop="order_price" label="付费单价"> </el-table-column>
        <el-table-column prop="visit_nums" label="访问数"> </el-table-column>
        <el-table-column prop="active_nums" label="活跃"> </el-table-column>
        <el-table-column prop="active_price" label="活跃单价"> </el-table-column>
        <el-table-column prop="log_d2" label="活跃(2)"> </el-table-column>
        <el-table-column prop="log_d3" label="活跃(3)"> </el-table-column>
        <el-table-column prop="log_d4" label="活跃(4)"> </el-table-column>
        <el-table-column prop="log_d7" label="活跃(7)"> </el-table-column>
        <el-table-column prop="log_d15" label="活跃(15)"> </el-table-column>
        <el-table-column prop="log_d30" label="活跃(30)"> </el-table-column>
        <el-table-column prop="pay_d1" label="充值(1)"> </el-table-column>
        <el-table-column prop="back_d1" label="回款率(1)"> </el-table-column>
        <el-table-column prop="pay_d2" label="充值(2)"> </el-table-column>
        <el-table-column prop="back_d2" label="回款率(2)"> </el-table-column>
        <el-table-column prop="pay_d3" label="充值(3)"> </el-table-column>
        <el-table-column prop="back_d3" label="回款率(3)"> </el-table-column>
        <el-table-column prop="pay_d7" label="充值(7)"> </el-table-column>
        <el-table-column prop="back_d7" label="回款率(7)"> </el-table-column>
        <el-table-column prop="pay_d15" label="充值(15)"> </el-table-column>
        <el-table-column prop="back_d15" label="回款率(15)"> </el-table-column>
        <el-table-column prop="pay_d30" label="充值(30)"> </el-table-column>
        <el-table-column prop="back_d30" label="回款率(30)"> </el-table-column>
      </el-table>
      <el-pagination
        class="tac"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pagination.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.perPages"
        layout="sizes, prev, pager, next"
        :total="pagination.total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
// 复制
export default {
  data() {
    return {
      flag: false,
      btnLoading: false,
      downloadLoading1: false,
      downloadLoading2: false,
      tableData: [], // 数据
      // dialog
      tableHeight: '', // 表格高度
      // 分页
      pagination: {
        total: 0, // 表格数据条数
        pages: 0, // 总页数
        perPages: 10, // 每页的数量
        currentPage: 1, // 当前页
      },
      // 查询
      queryServerInfo: {
        page: 1, // 第一页默认第一(非必填)
        per_page: 10, // 每页数量默认10(非必填)
      },
      // 分类
      total_category: [],
      queryTime: [new Date(new Date().getTime() - 1 * 24 * 60 * 60 * 1000), new Date(new Date().getTime() - 1 * 24 * 60 * 60 * 1000)],
      columns: [], //  存储合计行每列的数据
    };
  },
  computed: {},
  created() {
    this.getCIDList();
    this.getCurrentScreen();
  },
  mounted() {},
  updated() {
    let _this = this;
    this.$nextTick(() => {
      _this.$refs['table_cid'].doLayout();
      _this.isViture = true;
    });
  },
  methods: {
    getSummaries(param) {
      let { columns } = param;
      this.columns = columns;
      return [];
    },
    getAllData() {
      return new Promise(resolve => {
        let allquery = this.deepClone(this.queryServerInfo);
        allquery.page = 1;
        allquery.per_page = 9999;
        this.$api.getCIDList(allquery).then(res => {
          if (res.code == 0 || res.code == 200) {
            if (res.data.length > 0) {
              const sums = [];
              const data = res.data;
              this.columns.forEach((column, index) => {
                if (index === 0) {
                  sums[index] = '合计';
                  return;
                }
                if (index === 1) {
                  sums[index] = '';
                  return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                  sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                      return prev + curr;
                    } else {
                      return prev;
                    }
                  }, 0);
                  sums[index].toFixed(1);
                } else {
                  sums[index] = 'N/A';
                }
              });
              const sums2 = sums.map(item => {
                if (typeof item == 'number' && String(item).indexOf('.') > -1) {
                  return item.toFixed(2);
                } else {
                  return item;
                }
              });
              let table = document.getElementsByClassName('el-table__footer')[0];
              let tr = table.children[1].children[0];
              let tds = tr.children;
              tr.style.height = '80px';
              let index = Array.from(tds).findIndex((item, index) => item == 'undefind');
              if (index == -1) {
                Array.from(tds).map((item, index) => (item.innerHTML = sums2[index]));
              }
            }
          }
        });
      });
    },
    goCCID(r) {
      let cid = r.cid;
      this.$router.push({
        path: '/ccid',
        query: {
          cid: cid,
          date_s: this.queryServerInfo.date_s,
          date_e: this.queryServerInfo.date_e,
        },
      });
    },
    // 查询
    searchWyServer(num = 0) {
      this.queryServerInfo.page = 1;
      // this.queryServerInfo.date_s = this.queryTime[0] ? this.toDate(this.queryTime[0]) : '';
      // this.queryServerInfo.date_e = this.queryTime[1] ? this.toDate(this.queryTime[1]) : '';
      this.getCIDList(this.queryServerInfo);
    },
    // 每页数量变化
    handleSizeChange(val) {
      this.queryServerInfo.per_page = val;
      this.getCIDList(this.queryServerInfo);
    },
    // 当前页
    handleCurrentChange(val) {
      this.queryServerInfo.page = val;
      this.getCIDList(this.queryServerInfo);
    },
    // 获取cid列表信息
    getCIDList(params) {
      this.tableLoading = true;
      this.queryServerInfo.date_s = this.queryTime[0] ? this.toDate(this.queryTime[0]) : '';
      this.queryServerInfo.date_e = this.queryTime[1] ? this.toDate(this.queryTime[1]) : '';
      let queryObj = params || this.queryServerInfo;
      this.$api.getCIDList(queryObj).then(res => {
        this.tableLoading = false;
        if (res.code == 0 || res.code == 200) {
          // 处理表格显示数据
          this.tableData = res.data;
          // 分页
          this.pagination.currentPage = res.page;
          this.pagination.pages = Math.ceil(res.full_count / res.per_page);
          this.pagination.total = res.full_count;
          this.pagination.perPages = res.per_page;
          // this.pagination.perPages = Math.ceil(res.full_count / res.per_page);
          this.getAllData();
        }
      });
    },
    // 重置
    reset() {
      this.queryTime = [];
      this.queryServerInfo.cid = '';
      this.queryServerInfo.date_s = '';
      this.queryServerInfo.date_e = '';
      this.queryServerInfo.page = 1;
      this.queryServerInfo.per_page = 10;
      this.pagination.currentPage = 1;
      this.pagination.perPages = 10;
      this.getCIDList(this.queryServerInfo);
    },
    // 处理 tableHeight
    getCurrentScreen() {
      let height = window.screen.availHeight;
      if (height <= 900) {
        this.tableHeight = '570';
      } else if (height <= 1100) {
        this.tableHeight = '690';
      } else if (height <= 1500) {
        this.tableHeight = '1040';
      }
    },
    // 下载excel
    async downloadExcel(flage) {
      let excel = '<table>';
      //设置表头
      let list;
      if (!flage) {
        // 当前页
        this.downloadLoading1 = true;
        list = this.tableData;
      } else {
        // 所有页
        this.downloadLoading2 = true;
        this.queryServerInfo.page = 1;
        this.queryServerInfo.per_page = 9999;
        list = await this.getCIDList(this.queryServerInfo);
      }
      let row =
        '<tr>' +
        '<td>序号</td>' +
        '<td>cid</td>' +
        '<td>消耗</td>' +
        '<td>注册</td>' +
        '<td>访问转化率</td>' +
        '<td>注册单价</td>' +
        '<td>创角</td>' +
        '<td>创角率</td>' +
        '<td>充值人数</td>' +
        '<td>充值金额</td>' +
        '<td>付费率</td>' +
        '<td>付费单价</td>' +
        '<td>访问数</td>' +
        '<td>活跃</td>' +
        '<td>活跃单价</td>' +
        '<td>活跃(2)</td>' +
        '<td>活跃(3)</td>' +
        '<td>活跃(4)</td>' +
        '<td>活跃(7)</td>' +
        '<td>活跃(15)</td>' +
        '<td>活跃(30)</td>' +
        '<td>充值(1)</td>' +
        '<td>回款率(1)</td>' +
        '<td>充值(2)</td>' +
        '<td>回款率(2)</td>' +
        '<td>充值(3)</td>' +
        '<td>回款率(3)</td>' +
        '<td>充值(7)</td>' +
        '<td>回款率(7)</td>' +
        '<td>充值(15)</td>' +
        '<td>回款率(15)</td>' +
        '<td>充值(30)</td>' +
        '<td>回款率(30)</td>' +
        '</tr>';
      //换行
      excel += row;
      let l = list.map((o, i) => {
        return `
        <tr>
          <td>${i + 1}</td>
          <td>${o.ccid}</td>
          <td>${o.totalcost}</td>
          <td>${o.reg_nums}</td>
          <td>${o.reg_rate}</td>
          <td>${o.reg_price}</td>
          <td>${o.role_nums}</td>
          <td>${o.role_rate}</td>
          <td>${o.order_nums}</td>
          <td>${o.order_money}</td>
          <td>${o.order_rate}</td>
          <td>${o.order_price}</td>
          <td>${o.visit_nums}</td>
          <td>${o.active_nums}</td>
          <td>${o.order_nums}</td>
          <td>${o.active_price}</td>
          <td>${o.log_d2}</td>
          <td>${o.log_d3}</td>
          <td>${o.log_d4}</td>
          <td>${o.log_d7}</td>
          <td>${o.log_d15}</td>
          <td>${o.log_d30}</td>
          <td>${o.pay_d1}</td>
          <td>${o.back_d1}</td>
          <td>${o.pay_d2}</td>
          <td>${o.back_d2}</td>
          <td>${o.pay_d3}</td>
          <td>${o.back_d3}</td>
          <td>${o.pay_d7}</td>
          <td>${o.back_d7}</td>
          <td>${o.pay_d15}</td>
          <td>${o.back_d15}</td>
          <td>${o.pay_d30}</td>
          <td>${o.back_d30}</td>
        </tr>`;
      });

      excel += l.join('');
      excel += '</table>';
      //利用时间起文件名称
      var date = new Date();
      var fileName = '渠道cid数据' + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + '号' + date.getHours() + '点' + date.getMinutes() + '分';
      this.tableToExcel(excel, fileName);
      this.downloadLoading1 = false;
      this.downloadLoading2 = false;
      this.reset();
    },
  },
};
</script>
<style lang='stylus' scoped>
body {
}

.el-dialog__body {
  padding: 10px 20px 30px !important;
}

.el-table .cell {
  white-space: pre-line;
}

.el-table {
  overflow: visible !important;
}

/deep/ .el-table {
  display: flex;
  flex-direction: column;
}

/* order默认值为0，只需将表体order置为1即可移到最后，这样合计行就上移到表体上方 */
/deep/ .el-table__body-wrapper {
  order: 1;
}
</style>
